package cn.controller;

import cn.service.DownloadService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by wsx on 2017/1/16.
 */
@Controller
public class DownloadController {

    @Autowired
    private DownloadService dnloadservice;

    @RequestMapping(value = "/download", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String index(HttpServletResponse resp,HttpSession session,ModelMap model) {
        model.addAttribute("filelist",dnloadservice.getfilelist());
        return "download";
    }

    @RequestMapping("/downloadfile")
    public String download(@RequestParam("filename") String fnewname, HttpServletRequest req, HttpServletResponse response, ModelMap model) throws IOException {
        String filename = dnloadservice.getfsname(fnewname);
        if(null == filename){
            model.addAttribute("state", "文件不存在");
            return "downloadstate";
        }
        String realPathprefix = req.getServletContext().getRealPath("filedic");
        File file=new File(realPathprefix+File.separator+fnewname);
        if(!file.exists())
        {
            model.addAttribute("state", "文件错误");
            return "downloadstate";
        }
        OutputStream out = null;
        try {
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String(filename.getBytes("utf-8"), "ISO8859-1"));
            out = response.getOutputStream();
            out.write(FileUtils.readFileToByteArray(file));
            out.flush();
            model.addAttribute("state", "正在下载");
            return "downloadstate";
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        model.addAttribute("state", "下载错误");
        return "downloadstate";
    }




}
